<template>
  <div class="knowledge-list">
    <div class="action-bar">
      <div class="search-wrapper">
        <div class="search-input">
          <i class="search-icon el-icon-search"></i>
          <input 
            type="text" 
            v-model="keyword" 
            placeholder="搜索问题内容" 
            @keyup.enter="handleSearch"
          />
          <button class="search-btn" @click="handleSearch">搜索</button>
        </div>
      </div>
      
      <div class="action-buttons">
        <button class="btn-primary" @click="$emit('create')">
          <i class="btn-icon el-icon-plus"></i>
          <span>添加知识</span>
        </button>
      </div>
    </div>
    
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="knowledgeList"
        style="width: 100%"
        :header-cell-style="{
          background: '#f9fafc',
          color: '#606266',
          fontWeight: '600',
          borderBottom: '2px solid #EBEEF5'
        }"
        :cell-style="{
          padding: '12px 0'
        }"
      >
        <el-table-column prop="ID" label="ID" width="80" align="center">
          <template #default="scope">
            <span class="user-id">{{ scope.row.ID }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="question" label="问题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="answer" label="答案" min-width="250" show-overflow-tooltip />
        <el-table-column prop="category" label="分类" min-width="120" />
        <el-table-column prop="tags" label="标签" min-width="150" show-overflow-tooltip />
        <el-table-column prop="access_count" label="访问次数" width="100" align="center" />
        <el-table-column prop="CreatedAt" label="创建时间" min-width="180">
          <template #default="{ row }">
            {{ new Date(row.CreatedAt).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div class="table-actions">
              <button 
                class="action-btn btn-danger"
                @click="handleDelete(row)"
              >
                删除
              </button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="table-footer">
        <el-pagination
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getKnowledgeList, deleteKnowledge, type KnowledgeItem } from '../../api/knowledge'

// 定义事件
const emit = defineEmits(['create', 'refresh'])

// 列表状态
const knowledgeList = ref<KnowledgeItem[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const keyword = ref('')

// 页面初始化
onMounted(() => {
  fetchKnowledgeList()
})

// 获取知识库列表
const fetchKnowledgeList = async () => {
  loading.value = true
  try {
    const res = await getKnowledgeList(
      currentPage.value,
      pageSize.value,
      keyword.value
    )
    
    if (res.data && res.data.items) {
      knowledgeList.value = res.data.items
      total.value = res.data.total || 0
    } else {
      knowledgeList.value = []
      total.value = 0
      console.error('Invalid knowledge list response:', res)
    }
  } catch (error) {
    console.error('Failed to fetch knowledge list:', error)
    ElMessage.error('获取知识库列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索知识库
const handleSearch = () => {
  currentPage.value = 1
  fetchKnowledgeList()
}

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchKnowledgeList()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchKnowledgeList()
}

// 删除知识
const handleDelete = (row: KnowledgeItem) => {
  ElMessageBox.confirm(
    `确定要删除此知识条目吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteKnowledge(row.ID)
      ElMessage.success('删除成功')
      fetchKnowledgeList()
      emit('refresh')
    } catch (error) {
      console.error('Failed to delete knowledge:', error)
      ElMessage.error('删除知识条目失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}
</script>

<style scoped lang="scss">
.knowledge-list {
  width: 100%;
}

/* 操作栏 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .search-wrapper {
    flex: 1;
    max-width: 500px;
    
    .search-input {
      position: relative;
      display: flex;
      align-items: center;
      
      .search-icon {
        position: absolute;
        left: 12px;
        color: #909399;
      }
      
      input {
        flex: 1;
        height: 40px;
        padding: 0 15px 0 36px;
        border: 1px solid #dcdfe6;
        border-radius: 4px 0 0 4px;
        font-size: 14px;
        
        &:focus {
          outline: none;
          border-color: #409eff;
        }
      }
      
      .search-btn {
        height: 40px;
        padding: 0 15px;
        border: none;
        border-radius: 0 4px 4px 0;
        background-color: #409eff;
        color: white;
        font-size: 14px;
        cursor: pointer;
        
        &:hover {
          background-color: #66b1ff;
        }
      }
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 10px;
    
    .btn-primary {
      display: flex;
      align-items: center;
      gap: 5px;
      height: 40px;
      padding: 0 15px;
      border: none;
      border-radius: 4px;
      background-color: #409eff;
      color: white;
      font-size: 14px;
      cursor: pointer;
      
      &:hover {
        background-color: #66b1ff;
      }
      
      .btn-icon {
        font-size: 16px;
      }
    }
  }
}

/* 表格卡片 */
.table-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
  
  .user-id {
    font-weight: 600;
    background-color: #ecf3ff;
    color: #3a7cfe;
    padding: 4px 8px;
    border-radius: 4px;
    display: inline-block;
    min-width: 36px;
    text-align: center;
  }
  
  .table-actions {
    display: flex;
    gap: 8px;
    
    .action-btn {
      padding: 4px 8px;
      border: none;
      border-radius: 4px;
      font-size: 12px;
      cursor: pointer;
      
      &.btn-danger {
        background-color: #fff2f0;
        color: #ff4d4f;
        
        &:hover {
          background-color: #ffccc7;
        }
      }
    }
  }
  
  .table-footer {
    padding: 15px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 